<?php
namespace app\data_magic\controller;

use cmf\controller\HomeBaseController;
use app\data_magic\logic\Scene;

/**
 * 基于Structure的前台页面
 */
class StructureController extends HomeBaseController
{
    public function getSceneAndMeta()
    {
        $id=input("table_id");
        $scene=new Scene();
        $meta=$scene->initWithStructure($id);
        if(!$meta){
            $this->error($scene->getError());
        }
        return [$scene,$meta];
    }
    public function showCreatePage()
    {
        list($scene,$meta)=$this->getSceneAndMeta();
        $this->assign($meta);
        return $this->fetch("insert");
    }
    public function submitCreateAction()
    {
        list($scene,$meta)=$this->getSceneAndMeta();
        $result=$scene->createRecord($_REQUEST);
        if($result===false){
            $this->error("插入失败");
        }
        $this->success("操作成功");
    }
    public function showListPage()
    {
        list($scene,$meta)=$this->getSceneAndMeta();
        $list=$scene->searchRecords();
        $this->assign($meta);
        $this->assign("list",$list);
        return $this->fetch("list");
    }
    public function showItemPage()
    {
        $data_id=input("id");
        if(!$data_id){
            $this->error("ID未定义");
        }
        list($scene,$meta)=$this->getSceneAndMeta();
        $item=$scene->getRecord($data_id);
        $this->assign($meta);
        $this->assign("item",$item);
        return $this->fetch("edit");
    }
    public function submitEditAction()
    {
        $data_id=input("id");
        if(!$data_id){
            $this->error("ID未定义");
        }
        list($scene,$meta)=$this->getSceneAndMeta();
        $result=$scene->updateRecord($data_id,$_REQUEST);
        if($result===false){
            $this->error("修改失败");
        }
        $this->success("操作成功");
    }
    public function deleteItem()
    {
        $data_id=input("id");
        if(!$data_id){
            $this->error("ID未定义");
        }
        list($scene,$meta)=$this->getSceneAndMeta();
        $result=$scene->removeRecords($data_id);
        if($result===false){
            $this->error("删除失败");
        }
        $this->success("操作成功");
    }
}
